package org.darkforest.common.services.impl;


import org.apache.commons.httpclient.*;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.lang.StringUtils;
import org.darkforest.common.logger.Logger;
import org.darkforest.common.services.MobileMsgService;
import org.darkforest.common.services.SettingService;
import org.darkforest.common.sms.HttpSender;
import org.darkforest.common.sms.SendMsg;
import org.darkforest.enums.SettingNameEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;

/**
 * Created by Administrator on 2017/5/3.
 */
@Service
public class MobileMsgServiceImpl implements MobileMsgService {


    @Autowired
    private SettingService settingService;



    /**
     * 发送手机短信接口
     *  @param mobile
     * @param msg
     */
    public String sendMobileMsg(String mobile, String msg){
        String res = "false";
        try{
            //int result= SendMsg.sendMsg(mobile, msg, 0);
            String url = settingService.getSettingInfo(SettingNameEnum.SEND_MOBILEMSG_URL);
            String account = settingService.getSettingInfo(SettingNameEnum.SEND_MOBILEMSG_ACCOUNT);
            String password = settingService.getSettingInfo(SettingNameEnum.SEND_MOBILEMSG_PASSWORD);
            String needstatus = settingService.getSettingInfo(SettingNameEnum.SEND_MOBILEMSG_NEEDSTATUS);
            boolean nsb = false;
            if ("true".equals(needstatus)) {
                nsb = true;
            }

            Logger.info(MobileMsgServiceImpl.class,"手机号==" +mobile + "--短信发送开始。。。。"+msg);
            if (StringUtils.isNotEmpty(url) && StringUtils.isNotEmpty(account) && StringUtils.isNotEmpty(password)) {
                String returnStr = HttpSender.batchSend(url, account, password, mobile, msg, nsb, null, null);
                //返回状态
                String resultCode = "";
                // 短信发送返回值 rss=20180205173432,0
                // 18020517343221497
                System.out.println("短信发送返回值 returnStr=" + returnStr);
                Logger.info(MobileMsgServiceImpl.class,"手机号==" +mobile + "--短信发送返回值 returnStr=" + returnStr);
                //包含换行符
                if(returnStr.indexOf("\n") != -1){
                    resultCode = returnStr.substring(returnStr.indexOf(",")+1, returnStr.indexOf("\n"));
                }else{
                    resultCode = returnStr.substring(returnStr.indexOf(",")+1);
                }

                //返回情况处理
                if("0".equals(resultCode)){
                    res="true";
                    System.out.println("短信发送成功");
                }else if("107".equals(resultCode)){
                    System.out.println("发送失败:手机号码格式错误");
                }else{
                    System.out.println("发送失败");
                }
            } else {
                Logger.info(MobileMsgServiceImpl.class,"短信发送参数:url、account、password 没有设定");
            }
        }catch (Exception e){
            e.printStackTrace();
            Logger.error(MobileMsgServiceImpl.class, e.getLocalizedMessage());
        }finally {
            return res;
        }
    }

    /**
     * @param mobiles 手机号码，多个号码使用","分割
     * @param msg
     * @return
     */
    public String batchSendMobileMsg(String[] mobiles, String msg) {

        HttpClient client = new HttpClient();
        GetMethod method = new GetMethod();
        try {
            URI base = new URI(settingService.getSettingInfo(SettingNameEnum.SEND_MOBILEMSG_URL), false);
            method.setURI(new URI(base, "HttpBatchSendSM", false));
            method.setQueryString(new NameValuePair[] {
                    new NameValuePair("account", settingService.getSettingInfo(SettingNameEnum.SEND_MOBILEMSG_ACCOUNT)),
                    new NameValuePair("pswd", settingService.getSettingInfo(SettingNameEnum.SEND_MOBILEMSG_PASSWORD)),
                    new NameValuePair("mobile", StringUtils.join(mobiles,",")),
                    new NameValuePair("needstatus", String.valueOf(settingService.getSettingInfo(SettingNameEnum.SEND_MOBILEMSG_NEEDSTATUS))),
                    new NameValuePair("msg", msg),
                    new NameValuePair("product", null),
                    new NameValuePair("extno", null),
            });
            int result = client.executeMethod(method);
            if (result == HttpStatus.SC_OK) {
                InputStream in = method.getResponseBodyAsStream();
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                byte[] buffer = new byte[1024];
                int len = 0;
                while ((len = in.read(buffer)) != -1) {
                    baos.write(buffer, 0, len);
                }
                return URLDecoder.decode(baos.toString(), "UTF-8");
            } else {
                throw new Exception("HTTP ERROR Status: " + method.getStatusCode() + ":" + method.getStatusText());
            }
        } catch (HttpException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            method.releaseConnection();
        }
        return "0";
    }
}
